<script setup lang="ts">
import { computed, defineAsyncComponent, onMounted, reactive, ref, shallowRef } from 'vue'
import { message } from 'ant-design-vue'
// 移除可能导致冲突的Modal导入，弹窗组件内部已导入
import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import type { ConsultTableModel, MenuModel } from '~@/api/menu/menu'
import { deleteApi, tree } from '~@/api/menu/menu'

// 异步引入弹窗组件
const CreateMenuModal = defineAsyncComponent(() => import('./create.vue'))
const EditMenuModal = defineAsyncComponent(() => import('./edit.vue'))

// 控制弹窗显示的状态
const createModalVisible = ref(false)
const editModalVisible = ref(false)
const currentMenuId = ref('')

// 直接使用ant-design-vue提供的message全局对象
// 不需要创建实例，直接使用导入的message对象
const columns = shallowRef([
  {
    title: 'ID',
    dataIndex: 'menuId',
    width: 200,
  },
  {
    title: '菜单名称',
    dataIndex: 'menuName',
  },
  {
    title: '菜单编码',
    dataIndex: 'menuCode',
  },
  {
    title: '菜单排序',
    dataIndex: 'menuSort',
  },
  {
    title: '状态',
    dataIndex: 'statusFlag',
  },
  {
    title: '父菜单',
    dataIndex: 'menuParentId',
  },
  {
    title: '路由地址',
    dataIndex: 'antdvRouter',
  },
  {
    title: '前端组件名',
    dataIndex: 'antdvComponent',
    ellipsis: true,
  },
  {
    title: '图标编码',
    dataIndex: 'antdvIcon',
  },
  {
    title: '外部链接地址',
    dataIndex: 'antdvLinkUrl',
    ellipsis: true,
  },
  {
    title: '非菜单显示页面的重定向url',
    dataIndex: 'antdvActiveUrl',
    ellipsis: true,
  },
  {
    title: '是否显示(Y-是，N-否)',
    dataIndex: 'antdvVisible',
    ellipsis: true,
  },
  {
    title: '乐观锁',
    dataIndex: 'versionFlag',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
  },
])
const loading = shallowRef(false)
const total = ref(0)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总数据位：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef<ConsultTableModel[]>([])
const formModel = reactive<MenuModel>({
  menuName: '',
  menuCode: '',
  menuSort: 0,
  statusFlag: 0,
  remark: '',
  antdvRouter: '',
  antdvComponent: '',
  antdvIcon: '',
  menuId: 0,
  menuParentId: 0,
  versionFlag: 0,
  delFlag: 'N',
  antdvLinkUrl: '',
  antdvActiveUrl: '',
  antdvVisible: '',
})

const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])

const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
      ellipsis: true,
    }
  })
})
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await tree({
      ...formModel,
    })
    dataSource.value = data.list ?? []
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formModel.menuName = ''
  formModel.menuCode = ''
  await init()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: MenuModel) {
  const close = message.loading('删除中......')
  try {
    const res = await deleteApi(record!.menuId)
    if (res.code === 200)
      await init()
    message.success('删除成功')
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

// 打开新增弹窗
function handleAdd() {
  createModalVisible.value = true
}

// 打开修改弹窗
function handleEdit(record: MenuModel) {
  currentMenuId.value = record.menuId.toString()
  editModalVisible.value = true
}

// 关闭弹窗后刷新数据
function handleModalClose() {
  createModalVisible.value = false
  init()
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="menuName" label="菜单名称">
              <a-input v-model:value="formModel.menuName" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="menuCode" label="菜单编码">
              <a-input v-model:value="formModel.menuCode" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :span="24" style="text-align: right">
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="查询表格">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-blue @click="handleEdit(scope?.record as MenuModel)">
                修改
              </a>
              <a c-error @click="handleDelete(scope?.record as MenuModel)">
                删除
              </a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
  </page-container>

  <!-- 新增菜单弹窗 -->
  <CreateMenuModal
    v-model:visible="createModalVisible"
    @close="handleModalClose"
  />

  <!-- 编辑菜单弹窗 -->
  <EditMenuModal
    v-model:visible="editModalVisible"
    :menu-id="currentMenuId"
    @close="handleModalClose"
  />
</template>
